package net.bat.web.api;

import java.util.List;
import java.util.Map;

import net.bat.dto.LoginInfo;
import net.bat.dto.ResultDTO;
import net.bat.entity.User;
import net.bat.rest.RestService;
import net.bat.service.account.AccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ApiController {
	@Autowired
	private AccountService accountService;
	@Autowired
	private RestService restService;

	@RequestMapping(value = "/auth", method = RequestMethod.POST)
	@ResponseBody
	public User authenticate(@RequestBody LoginInfo request) {
		return accountService.login(request);
	}

	@RequestMapping(value = "/rest/{entity}", method = RequestMethod.GET)
	@ResponseBody
	public ResultDTO getEntities(@PathVariable String entity, @RequestParam(value = "page", required = true) int page,
			@RequestParam(value = "start", required = true) int start,
			@RequestParam(value = "limit", required = true) int limit,
			@RequestParam(value = "filter", required = false) String filter,
			@RequestParam(value = "sort", required = false) String sort) throws Exception {
		return restService.getEntities(page, start, limit, filter, sort, entity);
	}

	@RequestMapping(value = "/rest/{entity}/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public <T> T updateEntity(@PathVariable String entity, @PathVariable Object id,
			@RequestBody Map<String, Object> rmap) throws Exception {
		return (T) restService.updateEntity(entity, id, rmap);
	}

	@RequestMapping(value = "/rest/{entity}", method = RequestMethod.POST)
	@ResponseBody
	public <T> T addEntity(@PathVariable String entity, @RequestBody Map<String, Object> rmap) throws Exception {
		return (T) restService.addEntity(entity, rmap);
	}

	@RequestMapping(value = "/rest/remove", method = RequestMethod.DELETE)
	@ResponseBody
	public <T> T removeEntity(@RequestBody Map<String, Object> rmap) throws Exception {
		String entity = (String) rmap.get("entity");
		List ids = (List) rmap.get("ids");
		return (T) restService.removeEntitys(entity, ids.toArray());
	}

}
